﻿"""Authentication endpoints."""

from __future__ import annotations

from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session

from ...deps import get_current_user, get_db
from ....models.user import User
from ....schemas.auth import (
    LoginRequest,
    Message,
    PasswordResetConfirm,
    PasswordResetDirect,
    PasswordResetRequest,
    TokenRefreshRequest,
)
from ....schemas.token import TokenPair
from ....schemas.user import UserCreate, UserOut
from ....services.auth_service import AuthService

router = APIRouter()


@router.post("/login", response_model=TokenPair)
def login(
    payload: LoginRequest,
    session: Session = Depends(get_db),
) -> TokenPair:
    """
    用户登录接口.

    支持"记住我"功能：
    - remember=False: token有效期30分钟（默认）
    - remember=True: token有效期30天
    """
    service = AuthService(session)
    tokens = service.authenticate(payload.username, payload.password, remember=payload.remember)
    session.commit()
    return tokens


@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def register(
    payload: UserCreate,
    session: Session = Depends(get_db),
) -> UserOut:
    service = AuthService(session)
    user = service.register(payload)
    session.commit()
    return UserOut.model_validate(user)


@router.post("/refresh", response_model=TokenPair)
def refresh_token(
    payload: TokenRefreshRequest,
    session: Session = Depends(get_db),
) -> TokenPair:
    service = AuthService(session)
    tokens = service.refresh(payload.refresh_token)
    session.commit()
    return tokens


@router.post("/forgot-password", response_model=Message, status_code=status.HTTP_202_ACCEPTED)
def forgot_password(
    payload: PasswordResetRequest,
    session: Session = Depends(get_db),
) -> Message:
    service = AuthService(session)
    service.request_password_reset(payload.email)
    session.commit()
    return Message(message="If the account exists, a reset link has been prepared.")


@router.post("/reset-password", response_model=Message)
def reset_password(
    payload: PasswordResetConfirm,
    session: Session = Depends(get_db),
) -> Message:
    service = AuthService(session)
    service.reset_password(payload.token, payload.new_password)
    session.commit()
    return Message(message="Password updated successfully.")


@router.post("/reset-password-direct", response_model=Message)
def reset_password_direct(
    payload: PasswordResetDirect,
    session: Session = Depends(get_db),
) -> Message:
    """简化版密码重置：无邮件确认，直接输入2次新密码."""
    service = AuthService(session)
    service.reset_password_direct(
        email=payload.email,
        new_password=payload.new_password,
        confirm_password=payload.confirm_password,
    )
    session.commit()
    return Message(message="Password reset successfully.")


@router.get("/me", response_model=UserOut)
def read_current_user(current_user: User = Depends(get_current_user)) -> UserOut:
    return UserOut.model_validate(current_user)
